package com.sduept.nwld.dataserver.controller.equipment.assessment;

import com.alibaba.fastjson.JSONObject;
import com.sduept.bigdata.equipment.assessment.model.inspection.InspectionStation;
import com.sduept.cim.ledger.enums.ManagementUnitEnum;
import com.sduept.cim.ledger.excetpion.ManagementUnitException;
import com.sduept.cim.ledger.manager.SubstationLedgerManager;
import com.sduept.cim.ledger.model.ManagementUnitDict;
import com.sduept.cim.ledger.model.SubstationLedger;
import com.sduept.cim.ledger.services.ManagementUnitService;
import com.sduept.cim.model.core.Substation;
import com.sduept.bigdata.web.jsf.controller.AbstractController;
import com.sduept.bigdata.weather.map.MapDataCache;
import org.apache.commons.lang3.StringUtils;
import org.primefaces.PrimeFaces;
import org.primefaces.event.NodeSelectEvent;
import org.primefaces.event.NodeUnselectEvent;
import org.primefaces.model.DefaultTreeNode;
import org.primefaces.model.TreeNode;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
import java.util.*;
@Named
@ViewScoped
public class InspectionStationSelectorController2 extends AbstractController{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1460358413146695979L;
	
	@Autowired
	private ManagementUnitService unitService;

	@Autowired
	private SubstationLedgerManager stationLedgerM;
	@Autowired
	private MapDataCache cc;
	
	/**
	 * 电压等级
	 */
	private String selectedVol = "0";
	
	/**
	 * 变电站树根节点
	 */
	private TreeNode stationRoot;
	/**
	 * 选中的变电站节点
	 */
	private TreeNode[] selectedSubStationNodes;
	/**
	 * 所有的变电站map缓存
	 */
	private Map<String, Substation> stationMap = new HashMap<String, Substation>();
	/**
	 * 所有的运维单位
	 */
	private List<ManagementUnitDict> allMaintenance;
	/**
	 * 所有的检修范围,<id,ManagementUnitDict>
	 */
	private Map<String,ManagementUnitDict> maintenanceScopesMap = new HashMap<String, ManagementUnitDict>();
	/**
	 * 返回的数据
	 */
	private String inspectSelfItemData = "";
	
	@PostConstruct
	public void init() {
		preInitStationTree();
	}
	/**
	 * 初始化变电站树的准备工作
	 */
	public void preInitStationTree() {
		stationMap = cc.getStationid_map();
		genMaintenanceScopesMap();
		try {
			allMaintenance = unitService.getAllMaintenanceManagements();
			initSubStationTree();
		} catch (ManagementUnitException e) {
			e.printStackTrace();
			addErrorMessage("获取所有的运维单位出错");
		}
	}
	/**
	 * 获取检修范围，封装成Map<id,ManagementUnitDict>
	 */
	private void genMaintenanceScopesMap() {
		try {
			List<ManagementUnitDict> allMaintenanceScopes = unitService.getAllMaintenanceScopes();
			for (ManagementUnitDict unit : allMaintenanceScopes) {
				maintenanceScopesMap.put(unit.getId(), unit);
			}
		} catch (ManagementUnitException e) {
			e.printStackTrace();
			addErrorMessage("获取全部的检修范围出错");
		}
	}
	/**
	 * 初始化变电站树
	 * 结构：一级节点：南方电网
	 * 二级节点：检修范围
	 * 三级节点：运维单位
	 * 四级节点：变电站
	 */
	private void initSubStationTree() {
		stationRoot = new DefaultTreeNode();
		try {
			String rootName = unitService.getManagementUnitRoot();
			if(StringUtils.isEmpty(rootName)) {
				rootName = "南方电网";
			}
			// 组织机构的根节点，即南方电网
			DefaultTreeNode rootNode = new DefaultTreeNode("root", rootName, stationRoot);
			// 获取检修范围
			List<ManagementUnitDict> firstLevelChilds = getUnitsByPidFromList(null);
			for (ManagementUnitDict unit : firstLevelChilds) {
				recursionGenChildNode(unit, rootNode);
			}
			rootNode.setExpanded(true);
		} catch (ManagementUnitException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 根据pid，从allMaintenance中获取pid符合条件的记录
	 * pid=null,从所有的运维单位中，获取一级单位，即如果某记录的父单位类型为检修范围，则该父部门设为运维单位的一级单位
	 * @param pid
	 * @return 
	 */
	private List<ManagementUnitDict> getUnitsByPidFromList(String pid) {
		List<ManagementUnitDict> result = new ArrayList<ManagementUnitDict>();
		if(null == pid) {
			Set<ManagementUnitDict> units = new HashSet<ManagementUnitDict>();
			for (ManagementUnitDict unit : allMaintenance) {
				if(maintenanceScopesMap.containsKey(unit.getPid())) {
					units.add(maintenanceScopesMap.get(unit.getPid()));
				}
			}
			result.addAll(units);
		} else {
			for (ManagementUnitDict unit : allMaintenance) {
				if(pid.equals(unit.getPid())) {
					result.add(unit);
				}
			}
		}
		sort(result);
		return result;
	}
	
	/**
	 * 递归查找下一级节点，
	 * @param dept
	 * @param treeNode
	 */
	private void recursionGenChildNode(ManagementUnitDict unit, TreeNode rootNode) {
		DefaultTreeNode treeNode = new DefaultTreeNode("maintenanceUnit", unit, rootNode);
		if(unit.getUnitType() == ManagementUnitEnum.MAINTENANCE_MANAGEMENT) {// 当类型为运维时，查找其下的变电站
			// 获取该部门下的变电站
			if("0".equals(selectedVol)) {
				selectedVol = null;
			}
			List<SubstationLedger> stationLedgers = stationLedgerM.querySubstationByVoltageAndMaintenanceUnit(selectedVol, unit);
			for (SubstationLedger ledger : stationLedgers) {
				Substation station = stationMap.get(ledger.getCimId());
				if(station != null)
					new DefaultTreeNode("station", station, treeNode);
			}
		}
		// 获取该部门下的子部门
		List<ManagementUnitDict> childs = getUnitsByPidFromList(unit.getId());
		for (ManagementUnitDict dict : childs) {
			recursionGenChildNode(dict, treeNode);
		}
	}
	/**
	 * 将ManagementUnitDict按ordered从高到低排序
	 * @param List<ManagementUnitDict>
	 */
	private void sort(List<ManagementUnitDict> list) {
		Collections.sort(list,new Comparator<ManagementUnitDict> () {
			@Override
			public int compare(ManagementUnitDict o1, ManagementUnitDict o2) {
				return o2.getOrdered()-o1.getOrdered();
			}
		});
	}
	/**
	 * 选择变电站后，重新构造树
	 */
	public void changeVoltage(){
		initSubStationTree();
		selectedSubStationNodes = null;
	}
	/**
	 * 处理变电站选中事件
	 */
	public void onStationNodeSelect(NodeSelectEvent event) {
		
	}
	/**
	 * 处理变电站取消选中事件
	 */
	public void onStationNodeUnSelect(NodeUnselectEvent event) {
		
	}
	/**
	 * 保存数据并关闭弹窗
	 * 需要传递的数据：分子公司(acceptScope）---供电局（acceptUnit）---变电站（id、name、voltagelevel
	 */
	public void saveAndClose() {
		JSONObject r = new JSONObject();
		List<InspectionStation> instations = new ArrayList<InspectionStation>();
		if(selectedSubStationNodes!=null&&selectedSubStationNodes.length>0) {
			for(int i=0;i<selectedSubStationNodes.length;i++) {
				TreeNode substationNode = selectedSubStationNodes[i];
				if(substationNode.getType().equals("station")) {
					Substation station = (Substation) substationNode.getData();
					if(station!=null) {
						ManagementUnitDict management = (ManagementUnitDict) substationNode.getParent().getData();
						ManagementUnitDict scope = (ManagementUnitDict) substationNode.getParent().getParent().getData();
						InspectionStation instation = new InspectionStation();
						instation.setAcceptScope(scope.getName());
						instation.setAcceptUnit(management.getName());
						instation.setStationId(station.getId());
						instation.setStationName(station.getName());
						instation.setVoltagelevel(station.getStandVoltagelevel());
						instations.add(instation);
					}
				}
			}
		}
		r.put("selectedInspectionStations", instations);
		inspectSelfItemData = r.toJSONString();
		PrimeFaces.current().executeScript("closeAndSave("+inspectSelfItemData+")");
	}
	public String getSelectedVol() {
		return selectedVol;
	}
	public void setSelectedVol(String selectedVol) {
		this.selectedVol = selectedVol;
	}
	public TreeNode getStationRoot() {
		return stationRoot;
	}
	public void setStationRoot(TreeNode stationRoot) {
		this.stationRoot = stationRoot;
	}
	public TreeNode[] getSelectedSubStationNodes() {
		return selectedSubStationNodes;
	}
	public void setSelectedSubStationNodes(TreeNode[] selectedSubStationNodes) {
		this.selectedSubStationNodes = selectedSubStationNodes;
	}
	
}
